class OutdoorAdvertisement extends React.Component {
    constructor(props) {
        super(props);
        this.page = 1;
        this.state = {
            list: ''
        }
    }

    componentDidMount() {
        layui.use(['form', 'laypage'], function () {
            this.form = layui.form();
            this.layer = layui.layer;
            this.refs.buildingSelectList.layuiInitComplete();
            this.refs.buildingSelectList.queryList();
            this.queryList(1);
        }.bind(this));
    }

    uploadImage = (event, resourceId, commCode, fileName, screenType) => {
        console.log('Selected file:', event.target.files[0]);
        postUpload("/cms/resource/redistributionOutdoorAdv.x", {
            file: event.target.files[0],
            resourceId: resourceId,
            commCode: commCode,
            fileName: fileName,
            screenType: screenType
        }, (event) => {
            console.log('event222: ', event.loaded / event.total * 100);
        }, (data) => {
            this.queryList(this.page);
        }, (error) => {

        });
    };

    deleteResource = (resourceId) => {
        const index = layui.layer.confirm('确定要删除？', {
            btn: ['确定', '取消']
        }, () => {
            let param = {};
            param.resource_id = resourceId;
            param.isApproved = "N";
            param.approvedState = "不显示显示门口机广告";
            param.isUpdateTime = true;
            postJson("/cms/resource/approvedState.x", $.param(param), () => {
                this.queryList(this.page);
                layer.close(index);
            });
        });
    };

    notificationUpdate = (commCode) => {
        let param = {};
        param.commCode = commCode;
        postJson("/cms/resource/notificationUpdate.x", $.param(param), function (ret) {

        });
    };

    queryList(page) {
        let param = {};
        param.pageSize = 1;
        param.typeCode = 'outdoor_image_ads';
        const commCode = this.refs.buildingSelectList.getDefCommCode();
        if (commCode && commCode !== '-1') {
            param.commCode = commCode;
            param.page = 1;
        } else {
            //保证通过之后还是在当前页
            param.page = page;
        }
        this.updateList(param);
    }

    updateList(param) {
        postJson('/cms/resource/findResourceByComm.x', $.param(param), (data) => {
            this.page = param.page;
            this.setState({
                list: data.data.list
            });
            if (param.page === 1) {
                layui.laypage({
                    cont: 'contentListPage'
                    , pages: Math.ceil(data.data.size / param.pageSize)
                    , jump: (row, first) => {
                        if (!first) {
                            param.page = row.curr;
                            this.updateList(param);
                        }
                    }
                });
            }
        })
    }

    defImageView = (comm_code, fileName, screenType, i) => {
        return (<td align='center'>
            <div style={{width: '100%'}}>
                <div style={{float: 'left', color: 'blue'}}>图片-{i + 1}</div>
                <div style={{float: 'right', marginBottom: 10}}>
                    <button type="button" className="layui-btn layui-btn-danger layui-btn-mini">
                        <i className="layui-icon"></i> 删除
                    </button>
                </div>
            </div>
            <hr/>
            <UploadFile accept="image/jpeg,image/jpg,image/png,image/gif"
                        onChange={(event) => this.uploadImage(event, null, comm_code, fileName, screenType)}>
                <div className="Center-Container" style={divImgStyle}>
                    <img className="Absolute-Center" style={imgStyle} src="/pic/upload_ioc.png"/>
                </div>
            </UploadFile>
            <hr/>
            无广告
        </td>)
    };

    comImageView = (row, fileName, screenType, view, advRow, i) => {
        let create_time, url;
        if (advRow.isApproved === "Y") {
            create_time = advRow.create_time;
            url = advRow.icon_url + "?" + Math.random();
        } else {
            create_time = "无广告";
            url = "/pic/upload_ioc.png";
        }
        view.push(
            <td align='center'>
                <div style={{width: '100%'}}>
                    <div style={{float: 'left', color: 'blue'}}>图片-{i + 1}</div>
                    <div style={{float: 'right', marginBottom: 10}}>
                        <button type="button" className="layui-btn layui-btn-danger layui-btn-mini"
                                onClick={() => this.deleteResource(advRow.resource_id, row.comm_code)}>
                            <i className="layui-icon"></i> 删除
                        </button>
                    </div>
                </div>
                <hr/>
                <UploadFile accept="image/jpeg,image/jpg,image/png,image/gif"
                            onChange={(event) => this.uploadImage(event, advRow.resource_id, row.comm_code, fileName, screenType)}>
                    <div className="Center-Container" style={divImgStyle}>
                        <img className="Absolute-Center" style={imgStyle} src={url}/>
                    </div>
                </UploadFile>
                <hr/>
                {create_time}
            </td>
        );
    };

    resourceView = (row) => {
        let view = [];
        let crossView = [];
        crossView.push(<td>横屏广告</td>);
        let verticalView = [];
        verticalView.push(<td>竖屏广告</td>);
        console.log('resourceList', row.resourceList);
        let permsAdv8 = hasPerms('property:assignedAdv8') || hasRoles('admin');
        let advCont = 4;
        if (permsAdv8) {
            advCont = 8;
        }
        for (let i = 0; i < advCont; i++) {
            const fileCrossName = "OutdoorAdvertising-" + (i + 1);
            const fileVerticalName = "OutdoorAdvertisingVertical-" + (i + 1);
            let crossRow, verticalRow;
            for (const k in row.resourceList) {
                const advRow = row.resourceList[k];
                if (advRow.description === fileCrossName) {
                    crossRow = advRow;
                } else if (advRow.description === fileVerticalName) {
                    verticalRow = advRow;
                }
            }
            if (crossRow) {
                this.comImageView(row, fileCrossName, 'cross', crossView, crossRow, i);
            } else {
                crossView.push(this.defImageView(row.comm_code, fileCrossName, 'cross', i));
            }
            if (verticalRow) {
                this.comImageView(row, fileVerticalName, 'vertical', verticalView, verticalRow, i);
            } else {
                verticalView.push(this.defImageView(row.comm_code, fileVerticalName, 'vertical', i));
            }
        }

        view.push(crossView);
        view.push(<br/>);
        view.push(verticalView);
        return view;
    };

    tbody() {
        if (this.state.list) {
            return this.state.list.map((array) => {
                return (<tr>
                    <td>{array.comm_code}</td>
                    <td>{array.comm_name}</td>
                    <td style={hasPerms('property:assignedAdv8') || hasRoles('admin') ? {overflow: 'scroll', overflowY: 'hidden'} : {}}>
                        {this.resourceView(array)}
                    </td>
                    <td>
                        <button type="button" className='layui-btn'
                                onClick={() => this.notificationUpdate(array.comm_code)}>通知更新
                        </button>
                    </td>
                </tr>)
            })
        }
    }

    selectCommCallback() {
        this.queryList(1);
    }

    render() {
        return <Frame header="门口机广告推送">
                <div style={{color: "red", marginBottom: 10}}>
                    <strong style={{color: "blue"}}>Tips：</strong>
                    竖屏广告功能需要竖屏门口机升级到【1.9.7.142】之后版本，之前版本只能上传横屏广告！图片分辨率横屏使用1280*800，竖屏使用800*1280
                </div>
                <form id="form" className="layui-form layui-form-pane">
                    <BuildingSelectList ref="buildingSelectList" isNotItem={true} isDef={true}
                                        selectCallback={(commCode) => this.selectCommCallback(commCode)}/>
                    <div style={{paddingBottom: '10px'}}>
                        <table className="layui-table" style={{
                            width: '100%',
                            borderCollapse: 'collapse',
                            tableLayout: 'fixed'
                        }}>
                            <colgroup>
                                <col width="150px"/>
                                <col width="150px"/>
                                <col/>
                                <col width="150px"/>
                            </colgroup>
                            <thead>
                            <tr>
                                <th>小区编号</th>
                                <th>小区名</th>
                                <th>当前广告图片</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            {this.tbody()}
                            </tbody>
                        </table>
                        < div style={{'float': 'right', 'margin-right': '1px'}} id="contentListPage"/>
                    </div>
                </form>
                <div style={{clear: "both"}}></div>
        </Frame>
    }
}

const divImgStyle = {
    border: '1px solid #CDCDC1',
    float: 'left',
    marginLeft: '10px',
    marginBottom: '10px',
    width: '150px',
    height: '150px'
};

const imgStyle = {
    'max-height': '90%',
    'max-width': '90%'
};

ReactDOM.render(
    <OutdoorAdvertisement/>,
    document.getElementById('root')
);
